<script>
export default {
  name: 'Conf'
}
</script>

<script setup>
import { ref, reactive, onActivated, onMounted, nextTick, watch } from 'vue'
import aiSwitch from './ai-switch.json'
import aiApi from './ai-api.json'
import aiSetting from './ai-setting.json'
import replySetting from './reply-setting.json'
import { ElMessage } from 'element-plus'
import { debounce } from 'lodash'

import AppForm from '@renderer/components/app-form/app-form'
import AppAutocomplete from '@renderer/components/app-autocomplete/app-autocomplete.vue'

const aiFormSetting = ref(aiSetting)
const replyFormSetting = ref(replySetting)
const form = reactive({})

const onSubmit = debounce(() => {
  // console.log('submit!', form)
  app
    .setConfig(JSON.stringify(form), 'ai')
    .then(() => {
      // ElMessage.success('保存成功')
    })
    .catch((err) => {
      console.log('setConfig', err)
      ElMessage.error('保存失败')
    })
}, 500)

async function getSetting() {
  await app
    .getConfig('ai')
    .then((res) => {
      Object.assign(form, res)
    })
    .catch((err) => {
      console.log('getConfig', err)
    })
}

onActivated(async () => {})

onMounted(async () => {
  await nextTick()
  await getSetting()
  watch(form, () => {
    onSubmit()
  })
})
</script>

<template>
  <div class="overflow-hidden m-4">
    <el-tabs model-value="AiSetting" class="demo-tabs">
      <!-- AI 设置 -->
      <el-tab-pane label="AI 设置" name="AiSetting">
        <el-card class="m-0" shadow="never">
          <AppForm v-model="form" :items="aiSwitch"></AppForm>
          <AppAutocomplete v-model="form" :items="aiApi"></AppAutocomplete>
          <AppForm v-model="form" :items="aiFormSetting"></AppForm>
        </el-card>
      </el-tab-pane>
      <!-- 回复设置 -->
      <el-tab-pane label="回复设置" name="reply">
        <el-card class="m-0" shadow="never">
          <AppForm v-model="form" :items="replyFormSetting"></AppForm>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
